/*******************************************************************************
 * 版权：北京润尼尔网络科技有限公司，保留所有版权<br>
 * 版本：v1.0.0<br>
 * 文件：CommandCopy.js<br>
 * 日期：2018年9月12日<br>
 * 作者: 孙燕宝<br>
 * 功能：添加图片命令<br>
 * 
 * 修改记录：<br>
 * 日期 描述 更新功能<br>
 ******************************************************************************/

window.makeNamespace(window,"Rainier.UI.V2");

/**
 * 类型名称：Rainier.UI.V2.CommandAddImg<br>
 * 类型功能：添加图片命令<br>
 */
Rainier.UI.V2.CommandAddImg = draw2d.command.Command.extend({
	
	NAME : "Rainier.UI.V2.CommandAddImg",
	
	/**
	 * 函数名称：Rainier.UI.V2.CommandAddImg.init<br>
	 * 函数功能：构造函数<br>
	 * 异常信息：无<br>
	 */
	init : function(context,editParts){
		this.context 		= context;
		this.editPart       = editParts.data[0];
		this.addInfo = {};
		this.deleteInfo = {};
		this.tabId = app.canvasId;
    		this.rootEditPart 	= this.context.getRootEditPart();
    		this.activeEditor = app.getContext().getActiveEditor();
		this._super();
	},
	
    /**
	 * 函数名称：Rainier.UI.V2.CommandCopy.execute<br>
	 * 函数功能：执行命令<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	execute:function(){
		var _this = this;
		var json = Rainier.UI.V2.Communication.CustomImg;
		var createdModel = this.deleteInfo.model;
		if(createdModel){
			var portList 	= this.deleteInfo.ports.clone();
			portList.each(function(index,port){
				createdModel.addPort(port);
			});
		}
		else{
			createdModel = Rainier.UI.V2.DeviceModelBuilder.buildModel(json);
		}

		//添加器件id
		if(!createdModel.property.modelProperty.id){
			createdModel.property.modelProperty.id = (new Date()).getTime();
		}

		var model = this.editPart.getModel();
		//选中器件的位置和属性
		var property = model.property;
		var modelProperty = property.modelProperty;
		var uiProperty = property.uiProperty;
		var parentX = uiProperty.x;
		var parentY = uiProperty.y;
		
		var newChildX = null;
		var newChildY = null;
		var parentPorts = [];
		var childPorts = [];
		var sPort = null;
		var tPort = null;
		var inputs   = model.getInputPorts();
		var outputs  = model.getOutputPorts();
		var hybrids  = model.getHybridPorts();
		
		inputs.each(function(i,p){
			parentPorts.push(p);
		});
		outputs.each(function(i,p){
			parentPorts.push(p);
		});
		hybrids.each(function(i,p){
			parentPorts.push(p);
		});
		$.each(parentPorts,function(index,port){
			if(port.property.modelProperty.locator.defaultY == uiProperty.height){
				sPort = port;
			}
		});
		if(modelProperty.children.length==0){
			newChildX = parentX+1/2*(uiProperty.width)-createdModel.property.uiProperty.width/2;
			newChildY = parentY + uiProperty.height + createdModel.property.uiProperty.width/3;
			
			if(createdModel){          
				var inputs   = createdModel.getInputPorts();
				var outputs  = createdModel.getOutputPorts();
				var hybrids  = createdModel.getHybridPorts();
				
				inputs.each(function(i,p){
					childPorts.push(p);
				});
				outputs.each(function(i,p){
					childPorts.push(p);
				});
				hybrids.each(function(i,p){
					childPorts.push(p);
				});
			}
			//添加新孩子
			var parentModel = this.editPart.getParent().getModel();
			parentModel.addChildModel(createdModel);
			createdModel.setPosition(newChildX,newChildY,false);
			//添加连线
			var connection = Rainier.UI.V2.Communication.ConnectionModel[1];
			connection.uuid = (new Date()).getTime();
			connection.modelProperty.direction = "vertical";
			for(var i=0;i<childPorts.length;i++){
				var port = childPorts[i];
				if(port.property.modelProperty.locator.defaultY==0){
					tPort = port;
					if(sPort){
						_this.activeEditor.makeConnection(sPort,tPort,connection);
					}
				}
			}
		}
		else{
			//新孩子右移
			var children = modelProperty.children;
			// var model = this.getModelById(children[children.length-1]);
			var searchedModel = this.getModelById(children[children.length-1]);
			if(searchedModel === null){
				searchedModel = this._getModelById(children[children.length-1]);
			}
			var sTypeName = searchedModel.property.modelProperty.typeName;
			if(sTypeName === "TextModelJson" || sTypeName === "TextModelOval" || sTypeName === "TextModelDiamond"){
				// newChildX = searchedModel.property.uiProperty.x + 150;
				if(searchedModel.property.uiProperty.width <= 180){
					newChildX = searchedModel.property.uiProperty.x + searchedModel.property.uiProperty.width/2 + 117 - 136 + 64;
				}else{
					newChildX = searchedModel.property.uiProperty.x + searchedModel.property.uiProperty.width - 136 + 64;
				}
			}else{
				newChildX = searchedModel.property.uiProperty.x + searchedModel.property.uiProperty.width/2 + 117 - 136 + 64;	
			}
			newChildY = searchedModel.property.uiProperty.y;
			//老孩子左移
			this.moveLeftTree(model,'left');
			this.moveRightTree(model,'right');
			this.moveChildren(children,'left');
			if(createdModel){          
				var inputs   = createdModel.getInputPorts();
				var outputs  = createdModel.getOutputPorts();
				var hybrids  = createdModel.getHybridPorts();
				//清空老孩子ports
				childPorts = [];
				
				inputs.each(function(i,p){
					childPorts.push(p);
				});
				outputs.each(function(i,p){
					childPorts.push(p);
				});
				hybrids.each(function(i,p){
					childPorts.push(p);
				});
			}
			//添加新孩子
			var parentModel = this.editPart.getParent().getModel();
			parentModel.addChildModel(createdModel);
			createdModel.setPosition(newChildX,newChildY,false);
			//添加连线
			var connection = Rainier.UI.V2.Communication.ConnectionModel[0];
			connection.modelProperty.direction = "vertical";
			connection.uuid = (new Date()).getTime();
			$.each(childPorts,function(index,port){
				if(port.property.modelProperty.locator.defaultY==0){
					tPort = port;
					if(sPort){
						var segment = connection.modelProperty.segments;
						//终点x
						var x = createdModel.property.uiProperty.x;
						segment[1].start_x = x+createdModel.property.uiProperty.width/2;
						segment[1].start_y = parentY+uiProperty.height;
						_this.activeEditor.makeConnection(sPort,tPort,connection);
					}
				}
			});
			// this.refreshConnection();
		}
		//判断器材展示栏中是否已存在该器材，若存在则不再再次向展示栏中添加
		var className = createdModel.property.modelProperty.typeName;
		var componentName = createdModel.property.modelProperty.componentName;
		this.addUsedPart(className,componentName);
		// console.log(data);
		//存储图片
		modelProperty.imgArr.push(createdModel.m_sUuid);
		
		//添加孩子信息
		var _id = createdModel.property.modelProperty.id;
		modelProperty.children.push(_id);
		//添加父主题信息
		createdModel.property.modelProperty.parent = property.modelProperty.id;

		//更新预览图
		// if(isSelectedPreview){
		// 	setTimeout(function(){
		// 		var img = $("#img-preview");
		// 		refreshPreview(img);
		// 	});
		// }
	},
    
	/**
	 * 函数名称：Rainier.UI.V2.CommandCopy.undo<br>
	 * 函数功能：撤销命令<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	undo:function(){
		var model = this.addInfo.createdModel;
		var modelProperty = this.editPart.getModel().property.modelProperty;
		var parentModel = this.editPart.getParent().getModel();
		// 删除已添加到已使用器材的器件
		var className = model.property.modelProperty.typeName;
		this.deleteUsedPart(className);

		this.deleteInfo=parentModel.removeChildModel(model);
		if(modelProperty.imgArr){
			var index = modelProperty.imgArr.indexOf(model.m_sUuid);
			modelProperty.imgArr.splice(index,1);
		}
		//父节点删除子信息
		var parentId = model.property.modelProperty.parent;
		var parent =  this.getModelById(parentId);
		if(parent){
			var children = parent.property.modelProperty.children;
			var _children = [];
			for(var i=0;i<children.length;i++){
				var _id = children[i];
				if(_id==id){
					var index = children.indexOf(_id);
					children.splice(index,1);
				}
				else{
					_children.push(_id);
				}
			}
			//老孩子移动到原位
			this.moveChildren(_children,'right');
			if(children.length>0){
				this.moveLeftTree(parent,'right');
				this.moveRightTree(parent,'left');
			}
		}
		// this.refreshConnection();
	},
    
	/**
	 * 函数名称：Rainier.UI.V2.CommandCopy.redo<br>
	 * 函数功能：重做命令<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	redo:function(){
		this.execute();
	},

	/**
     	 * 函数名称：Rainier.UI.V2.CommandAddTheme.addUsedPart<br>
     	 * 函数功能：(单个添加器件)判断器材展示栏中是否已存在该器材，若存在则不再再次向展示栏中添加<br>
     	 * 函数输入：className和componentName
     	 * 函数返回：无<br>
     	 * 异常信息：无<br>
     	 */
	addUsedPart : function(className,componentName){
		// if(className === "OverThreeTextModelJson" || className === "TextModelJson2" || className === "TextModelJson3"){
		// 	className = "TextModelJson";
		// }
		var usedPart = {};
		usedPart.isLogic = true;
		usedPart.courseType = "Communication";
		usedPart.deviceType = "PmsModel";
		//data_part:data的一个对象
		var data_part = {};
		data_part.className = className;
		// 还未向实验台添加器件时
		if(data.length == 0){
			if(className){
				data_part.addCount = 1;
			}
			data.push(data_part);
			usedPart.className = data[0].className;
			usedPart.componentName = componentName;
			usedPartArray.push(usedPart);
			// console.log(data);
			// console.log(usedPartArray);
		// 实验台上已经存在器件时
		}else{
			for(var i=0;i<data.length;i++){
				if(data[i].className == className){
					// console.log("已加入已使用器件数组!");
					data[i].addCount += 1;
					// console.log(data);
					return;
				}
			}
			data_part.addCount = 1;
			data.push(data_part);
			usedPart.className = data[data.length-1].className;
			usedPart.componentName = componentName;
			usedPartArray.push(usedPart);
			// console.log(data);
			// console.log(usedPartArray);
		}
		// console.log(data);
		// console.log(usedPartArray);
	},

	/**
	 * 函数名称：Rainier.UI.V2.CommandAdd.deleteUsedPart<br>
	 * 函数功能：根据addCount的值删除器件展示栏中的器件，若为0，则删除<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	deleteUsedPart : function(className){
		if(className){
			for(var i=0;i<data.length;i++){
				if(className == data[i].className){
					data[i].addCount -=1;
					if(data[i].addCount > 0){
						// console.log(data);
						// console.log(usedPartArray);
						// console.log("实验台上还存在"+className);
						return;
					}else{
						data.splice(i, 1);
						// console.log(data);
						// addCount<=0且usedPartArray中存在该className对应的器件信息时，将该器件从器件展示栏删除
						for(var j=0;j<usedPartArray.length;j++){
							if(usedPartArray[j].className == className){
								usedPartArray.splice(j, 1);
								// console.log(usedPartArray);
							}
						}
					}
				}
			}
		}
	},
	
	/**
	 * 函数名称：Rainier.UI.V2.CommandCopy.getModelById<br>
	 * 函数功能：根据主题id查询对应model<br>
	 * 参数输入：无<br>
	 * 参数输出：无<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	getModelById : function(id){
		var parentModel = this.editPart.getParent().getModel();
		var children = parentModel.m_aChildren;
		var model = null;
		if(children){
			$.each(children,function(index,child){
				var _id = child.property.modelProperty.id;
				if(_id==id){
					model = child;
				}
			});
		}
		return model;
	},

	/**
	 * 函数名称：Rainier.UI.V2.CommandCopy._getModelById<br>
	 * 函数功能：根据主题id在已经隐藏图片库查询对应model<br>
	 * 参数输入：无<br>
	 * 参数输出：无<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	_getModelById : function(id){
		var model = null;
		var hideArr = hideImgArr[this.tabId];
		if(hideArr){
			if(hideArr.length>0){
				$.each(hideArr,function(index,deleteInfo){
					var _id = deleteInfo.model.property.modelProperty.id;
					if(_id==id){
						model = deleteInfo.model;
					}
				});
			}
		}
		return model;
	},

	/**
	 * 函数名称：Rainier.UI.V2.CommandAddTheme.moveLeftTree<br>
	 * 函数功能：新建主题用的递归函数<br>
	 * 参数输入：无<br>
	 * 参数输出：无<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	moveLeftTree : function(model,direction){
		var parent = model.property.modelProperty.parent;
		if(parent){
			var parentModel = this.getModelById(parent);
			var children = parentModel.property.modelProperty.children;
			var modelId = model.property.modelProperty.id;
			var index = children.indexOf(modelId);
			var childrenLeft = children.slice(0,index);
			this.moveChildren(childrenLeft,direction);
			this.moveLeftTree(parentModel,direction);
		}
	},

	/**
	 * 函数名称：Rainier.UI.V2.CommandAddTheme.moveRightTree<br>
	 * 函数功能：新建主题用的递归函数<br>
	 * 参数输入：无<br>
	 * 参数输出：无<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	moveRightTree : function(model,direction){
		var parent = model.property.modelProperty.parent;
		if(parent){
			var parentModel = this.getModelById(parent);
			var children = parentModel.property.modelProperty.children;
			var modelId = model.property.modelProperty.id;
			var index = children.indexOf(modelId);
			var childrenRight = children.slice(index+1);
			this.moveChildren(childrenRight,direction);
			this.moveRightTree(parentModel,direction);
		}
	},

    	/**
	 * 函数名称：Rainier.UI.V2.CommandAddTheme.moveChildren<br>
	 * 函数功能：新建主题用的递归函数<br>
	 * 参数输入：无<br>
	 * 参数输出：无<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	moveChildren : function(children,direction){
		var _this = this;
		for(var i=0;i<children.length;i++){
			var _id = children[i];
			var childModel = this.getModelById(_id);
			if(childModel === null){
				childModel = this._getModelById(_id);
			}
			var uiProperty = childModel.property.uiProperty;
			var x = uiProperty.x;
			var y = uiProperty.y;
			var oldChildX = null;
			if(direction=='left'){
				oldChildX = x - 136;
			}
			if(direction=='right'){
				oldChildX = x + 136;
			}
			var oldChildY = y;
			//更新老孩子位置
			childModel.setPosition(oldChildX,oldChildY,false);
			var _children = childModel.property.modelProperty.children;
			if(direction=='left'){
				if(_children){
					_this.moveChildren(_children,'left');
				}
			}
			if(direction=='right'){
				if(_children){
					_this.moveChildren(_children,'right');
				}
			}
		}
	},

 	/**
	 * 函数名称：Rainier.UI.V2.CommandAddTheme.refreshConnection<br>
	 * 函数功能：重新绘制连线<br>
	 * 参数输入：无<br>
	 * 参数输出：无<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	refreshConnection : function(){
		//删除错误连线
		//遍历三次，否则不能删除干净
		var connections = this.activeEditor.rootModel.connections.data;
		var _connection = Rainier.UI.V2.Communication.ConnectionModel[0];
		
		for(var j=0;j<3;j++){
			connections = this.activeEditor.rootModel.connections.data;
			for(var i=0;i<connections.length;i++){
				var connection = connections[i];
				// 只刷新竖向连线
				if(connection.property.modelProperty.direction !== "undefined" && connection.property.modelProperty.direction== "vertical"){
					var segments = connection.property.modelProperty.segments;
					if(segments.length>1){
						if(segments[0].type=="vertical"||segments[1].type=="horizontal"){
							//确保新线完成再删除错误
							var complete = false;
							//确保id相同
							_connection.uuid = connection.m_sUuid;
							//删除连线
							var sourcePort = connection.sourcePort;
							var targetPort = connection.targetPort;
							var _segment = connection.property.modelProperty.segments;
							var x = _segment[1].end_x;
							var y = _segment[0].start_y;
							if(sourcePort){
								var segment = _connection.modelProperty.segments;
								segment[1].start_x = x;
								segment[1].start_y = y;
								this.activeEditor.makeConnection(sourcePort,targetPort,_connection);
							}
							complete = true;
							if(complete){
								this.rootEditPart.getModel().removeConnection(connection);
							}
						}
					}
				}
				
			}
		}
	},
});